import React from 'react';
import {Spin, Card, Button, Table} from 'antd';
import PropTypes from 'prop-types';
import routes from './routes';
import {TABLE, DATE_FORMAT} from '../constants';
import {PERMISSION} from './constants';
import {hasPermissions} from './utils';
import {injectIntl} from './intl';
import styles from './style.css';
import DeliveryOrderMultiPanel from './DeliveryOrderMultiPanel';
import Return from '../common/Return';
import {postingValidator} from './validator';
import {formatAmount, conventEnumValueToString, formatDateTime} from '../utils';
import {currency, transportType, partDeliveryType} from '../Enum';

class PostingPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        data: {},
        showDeliveryOrderSelectPanel: false,
        details: []
    }
    componentWillUnmount() {
        this.isunmount = true;
    }
    onSelectDeliveryOrder = records => {
        const deliveryDetails = this.state.details || [];
        records.forEach(r => {
            const index = deliveryDetails.findIndex(v => v.deliveryOrderId === r.id);
            if(index === -1)
                deliveryDetails.push({
                    deliveryOrderId: r.id,
                    sapDeliveryCode: r.sapDeliveryCode,
                    sapTransferOrderCode: r.sapTransferOrderCode,
                    partSaleOrderCode: r.partSaleOrderCode,
                    itemCount: r.itemCount,
                    totalAmount: r.totalAmount,
                    partOrderTypeName: r.partOrderTypeName,
                    transportType: r.transportType,
                    submitDate: r.submitDate,
                    currency: r.currency,
                    dealerCode: r.dealerCode,
                    status: r.status,
                    rowVersion: r.rowVersion
                });
        });
        this.setState({
            details: deliveryDetails,
            hasOperat: true,
            showDeliveryOrderSelectPanel: false
        });
    }
    onClickSearchBtn = () => {
        this.setState({showDeliveryOrderSelectPanel: true});
    }
    onCloseDeliveryOrderSelectPanel = () => {
        this.setState({showDeliveryOrderSelectPanel: false});
    }
    onClickOkOnPopconfirm = () => {
        this.props.onCancel();
    }
    onSubmit = () => {
        const {details} = this.state;
        const isValid = postingValidator(details);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({loading: true});
        this.props.onSubmit(details).then(res => {
            if(res.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }
    onClickAddBtn = () => {
        this.setState({showDeliveryOrderSelectPanel: true});
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {loading, details} = this.state;
        const submitable = !hasPermissions(PERMISSION.posting, this.props.permissions);
        const currentSelectRowkeys = details.map(item => item.sapDeliveryCode);
        const colums = [{
            title: formatMessage({
                id: 'postingPanel.column.sapDeliveryCode',
                defaultMessage: 'SAP交货单号'
            }),
            dataIndex: 'sapDeliveryCode',
        }, {
            title: formatMessage({
                id: 'postingPanel.column.sapTransferOrderCode',
                defaultMessage: 'SAP备件调拨单号'
            }),
            dataIndex: 'sapTransferOrderCode',
        }, {
            title: formatMessage({
                id: 'postingPanel.column.dealerCode',
                defaultMessage: '服务站编号'
            }),
            dataIndex: 'dealerCode',
        }, {
            title: formatMessage({
                id: 'postingPanel.column.partSaleOrderCode',
                defaultMessage: '备件销售订单编号'
            }),
            dataIndex: 'partSaleOrderCode',
        }, {
            title: formatMessage({
                id: 'postingPanel.column.partOrderTypeName',
                defaultMessage: '订单类型'
            }),
            dataIndex: 'partOrderTypeName',
        }, {
            title: formatMessage({
                id: 'postingPanel.column.status',
                defaultMessage: '状态'
            }),
            dataIndex: 'status',
            render: text => conventEnumValueToString(partDeliveryType, text)
        }, {
            title: formatMessage({
                id: 'postingPanel.column.submitDate',
                defaultMessage: '订单提报日期'
            }),
            dataIndex: 'submitDate',
            render: text => formatDateTime(text, DATE_FORMAT)
        }, {
            title: formatMessage({
                id: 'postingPanel.column.currency',
                defaultMessage: '币种'
            }),
            dataIndex: 'currency',
            render: text => conventEnumValueToString(currency, text)
        }, {
            title: formatMessage({
                id: 'postingPanel.column.transportType',
                defaultMessage: '运输方式'
            }),
            dataIndex: 'transportType',
            render: text => conventEnumValueToString(transportType, text)
        }, {
            title: formatMessage({
                id: 'postingPanel.column.itemCount',
                defaultMessage: '品种数'
            }),
            dataIndex: 'itemCount',
        }, {
            title: formatMessage({
                id: 'postingPanel.column.totalAmount',
                defaultMessage: '总金额'
            }),
            dataIndex: 'totalAmount',
            render: text => formatAmount(text)
        }];
        return (
            <div className="form-standard">
                <Spin spinning={this.state.loading}>
                    <Card title={formatMessage({
                        id: 'postingPanel.column.common',
                        defaultMessage: '备件交货单'
                    })}
                    extra={<Button
                        size="small"
                        onClick={this.onClickAddBtn}>
                        {formatMessage({
                            id: 'postingPanel.operation.newDetail',
                            defaultMessage: '添加交货单'
                        })}
                    </Button>}>
                        <Table
                            className="white-space-nowrap"
                            columns={colums}
                            rowKey="id"
                            pagination={false}
                            dataSource={details}
                            {...TABLE} />
                    </Card>
                    <Card className={styles.optionBtn}>
                        <Button
                            type="primary"
                            onClick={this.onSubmit}
                            disabled={!submitable}
                            loading={loading}>
                            {formatMessage({
                                id: 'postingPanel.operation.onSave',
                                defaultMessage: '保存'
                            })}
                        </Button>
                    </Card>
                    {
                        this.state.showDeliveryOrderSelectPanel &&
                        <DeliveryOrderMultiPanel
                            currentSelectRowkeys={currentSelectRowkeys}
                            isDelivery={false}
                            selectKey={this.state.partId}
                            onCancel={this.onCloseDeliveryOrderSelectPanel}
                            onSelect={this.onSelectDeliveryOrder} />
                    }
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        onConfirm={this.onClickOkOnPopconfirm}
                        showWarning={this.state.hasOperat} />
                </div>
            </div>
        );
    }
}

PostingPanel.propTypes = {
    permissions: PropTypes.array.isRequired,
    successReturn: PropTypes.func.isRequired,
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    history: PropTypes.object,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import {
    tableSearch,
    onPosting
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = (state, props) => ({
    permissions: getPermissions(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    onSubmit: data => dispatch(onPosting(data)),
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(PostingPanel));
